/**
 * merge level=30
 * 
 * 
 */

Ext.define('Jfok.report.resultgrid.ResultListGridStore', {
	extend : 'Ext.data.Store',

	remoteSort : true,
	autoLoad : true,
	autoSync : false,

	extraParams : {},
	navigates : [],

	constructor : function(param) {

		this.grid = param.grid;
		this.module = param.module;
		this.groupAndFields = param.groupAndFields;
		this.model = this.getModel(this.module, this.groupAndFields); // 'Jfok.report.ResultListGridModel';
		this.pageSize = Jfok.system.pageSize;

		if (this.grid.mainReport.getIsLiveGrid()) {
			// live grid 加上以下几行
			this.remoteGroup = true;
			this.buffered = true;
			this.leadingBufferZone = 200;
			this.pageSize = 100
		}

		this.proxy = {
			type : 'rest',
			batchActions : true,
			url : 'report/fetchdata.do',
			actionMethods : {
				read : 'POST'
			},
			reader : {
				type : 'json',
				root : 'records',
				totalProperty : 'totalCount'
			}
		}
		this.callParent(arguments);

	},

	listeners : {
		// 调用proxy进行ajax的时候，将参数加进 store.proxy中，在调用完成后，删除掉所有的extraParams参数
		// 这样model.proxy就可以多store，互相不干扰了
		beforeprefetch : function(store) {
			for (var i in store.extraParams)
				store.proxy.extraParams[i] = store.extraParams[i];
		},
		// buffered = true ,执行的是 prefetch
		prefetch : function(store, records, successful) {
			for (var i in store.extraParams)
				delete store.proxy.extraParams[i];
		},

		// buffered = false ,执行的是 load
		beforeload : function(store) {
			var report = this.grid.up('mainreport');
			var conditionList = report.down('conditionlistgrid');
			store.proxy.extraParams['groupFields'] = Ext.encode(report
					.getGroupFields());
			store.proxy.extraParams['groupShowDetail'] = report.getGroupShowDetail();
			var conditions = [];
			conditionList.getStore().each(function(record) {
						conditions.push({
									type : record.get('type'),
									conditionId : record.get('conditionId'),
									values : record.get('se_values')
								})
					});
			store.proxy.extraParams['moduleConditions'] = Ext.encode(conditions);
			store.proxy.extraParams['selectedFields'] = Ext.encode(report
					.changeGroupAndFieldsToMin(report.getSelectdGroupAndFields()));

			store.proxy.extraParams['reportGroupId'] = report.reportGroup.reportGroupId;
			store.proxy.extraParams['reportId'] = report.getReportId();
			store.proxy.extraParams['baseModuleName'] = report.getBaseModuleName(); // 当前选中的基准模块
			store.proxy.extraParams['isShowTotal'] = report.getIsShowTotal(); // 是否要显示总计行

		},

		load : function(store, records) {
			if (store.data.length > 0)
				store.grid.columnsAutoSize();
		}
	},

	getModel : function(module, groupAndFields) {
		if (!module)
			return null;
		var model = Ext.define('Jfok.model.report.model', {
					mixins : ['Jfok.module.model.ApproveBase'],

					extend : 'Ext.data.Model',
					module : module,
					idProperty : module.tf_primaryKey,
					nameFields : module.tf_nameFields,
					titleTpl : module.tf_titleTpl,
					titleTemplate : null,
					fields : this.getFields(module, groupAndFields),

					getTitleTpl : function() {
						if (!this.titleTemplate) {
							if (this.titleTpl)
								this.titleTemplate = new Ext.Template(this.titleTpl);
							else
								this.titleTemplate = new Ext.Template('{' + this.nameFields
										+ '}');
						}
						return this.titleTemplate.apply(this.getData())
					},

					// 取得主键值
					getIdValue : function() {
						return this.get(this.idProperty);
					},

					// 取得当前记录的名字字段
					getNameValue : function() {
						if (this.nameFields)
							return this.get(this.nameFields);
						else
							return null;
					}

				});
		return model;

	},

	// 和成本模块的所有字段
	getFields : function(module, groupAndFields) {
		var fields = [{
					name : '_total_',
					type : 'string'
				}, {
					name : '_level_',
					type : 'int'
				}, {
					name : '_count_',
					type : 'int'
				}];

		if (module.tf_hasAddition) {
			fields.push({
						name : 'tf_additionCount',
						title : '附件张数',
						persist : false,
						type : 'int'
					})
		}
		for (var i in module.moduleFields) {
			var fd = module.moduleFields[i];

			if (fd.manyToOne || fd.oneToOne) { // 如果是manytoone ,one to one
				// 的字段，加入id 和 name
				fields.push({
							name : fd.manytoone_IdName,
							// title : fd.tf_title+ "序号",
							useNull : true,
							type : 'string',
							serialize : this.convertToNull
						});

				fields.push({
							name : fd.manytoone_TitleName,
							title : fd.tf_title,
							persist : false, // 此字段不会被提交到insert,update中
							type : 'string'
						});

			} else {
				var field = {
					name : fd.tf_fieldName,
					title : fd.tf_title,
					type : this.getTypeByStr(fd.tf_fieldType)
				};
				if (field.type == 'string') {
					field.useNull = true;
					field.serialize = this.convertToNull;
				}
			}
			if (fd.tf_fieldType == 'Date') {
				field.dateWriteFormat = 'Y-m-d';
				field.dateReadFormat = 'Y-m-d';
			}
			if (fd.tf_fieldType == 'Datetime')
				field.dateReadFormat = 'Y-m-d H:i:s';
			field.tf_haveAttachment = fd.tf_haveAttachment;
			fields.push(field);
		}
		fields = fields.concat(this.getParentFields(groupAndFields));

		// console.log('all fields');
		// console.log(this.getParentFields(groupAndFields));

		return fields;

	},

	// 用于生成选择过程中的 父模块的各个字段
	getParentFields : function(groupAndFields) {
		var fields = [];
		var me = this;
		Ext.Array.forEach(groupAndFields, function(group) {
			Ext.Array.forEach(group.fields, function(field) {
						// 不是当前基准模块
						if (field.moduleName != me.module.tf_moduleName) {
							var pmodule = Jfok.modules
									.getModuleInfoWithName(field.moduleName);
							var f = me.getAParentField(pmodule, field.fieldId, fields, field);
							if (f)
								fields.push(f);
						}
					})
		})
		return fields;
	},

	// 增加一个父模块的字段，字段前面加 _t9999___,
	getAParentField : function(module, fieldId, fields, fd1) {
		var fd = null;
		for (var i in module.moduleFields) {
			if (module.moduleFields[i].tf_fieldId == fieldId) {
				fd = module.moduleFields[i];
				break;
			}
		}
		if (fd == null)
			return null;
		if (fd.manyToOne || fd.oneToOne) { // 如果是manytoone ,one to one
			// 的字段，加入id 和 name
			fields.push({
						name : fd.manytoone_IdName,
						// title : fd.tf_title+ "序号",
						useNull : true,
						type : 'string',
						serialize : this.convertToNull
					});

			fields.push({
						name : fd.manytoone_TitleName,
						title : fd.tf_title,
						persist : false, // 此字段不会被提交到insert,update中
						type : 'string'
					});

		} else {
			var field = {
				name : module.tableAsName + '___' + fd.tf_fieldName,
				title : fd.tf_title,
				type : this.getTypeByStr(fd.tf_fieldType)
			};

			if (field.type == 'string') {
				field.useNull = true;
				field.serialize = this.convertToNull;
			}

			if (fd.tf_fieldType == 'Date') {
				field.dateWriteFormat = 'Y-m-d';
				field.dateReadFormat = 'Y-m-d';
			}
			if (fd.tf_fieldType == 'Datetime')
				field.dateReadFormat = 'Y-m-d H:i:s';
			field.tf_haveAttachment = fd.tf_haveAttachment;
		}

		if (fd1.aggregateType == 'sum') {
			field.name = 'S_' + field.name;
			field.title += '小计';
		} else if (fd1.aggregateType == 'count') {
			field.name = 'C_' + field.name;
			field.title += '个数';
			field.type = 'int';
		} else if (fd1.aggregateType == 'avg') {
			field.name = 'A_' + field.name;
			field.title += '均值';
		} else if (fd1.aggregateType == 'max') {
			field.name = 'X_' + field.name;
			field.title += '最大值';
		} else if (fd1.aggregateType == 'min') {
			field.name = 'N_' + field.name;
			field.title += '最小值';
		}

		return field;
	},

	getTypeByStr : function(str) {
		switch (str) {
			case 'String' :
				return 'string';
			case 'Boolean' :
				return 'boolean';
			case 'Integer' :
				return 'int';
			case 'Date' :
				return 'date';
			case 'Datetime' :
				return 'date';
			case 'Double' :
			case 'Float' :
			case 'Percent' :
				return 'float';
			default :
				return 'string';
		}
	}
});
